<template>
  <div class="order-list-page">
    <div class="page-header">
      <h2>我的订单</h2>
    </div>

    <div class="order-filter">
      <div class="filter-item">
        <label>订单状态：</label>
        <select v-model="filterStatus">
          <option value="">全部</option>
          <option value="0">已取消</option>
          <option value="1">待付款</option>
          <option value="2">待发货</option>
          <option value="3">待收货</option>
          <option value="4">已完成</option>
        </select>
      </div>
      <div class="filter-item">
        <input
          v-model="searchKeyword"
          type="text"
          placeholder="搜索订单号或商品名称"
          class="search-input"
        />
        <button @click="searchOrders" class="search-btn">搜索</button>
      </div>
    </div>

    <div class="order-list-container">
      <!-- 加载状态 -->
      <div v-if="loading" class="loading-container">
        <div class="spinner"></div>
        <p>加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div v-else-if="error" class="error-container">
        <i class="fa fa-exclamation-circle"></i>
        <p>{{ errorMessage }}</p>
        <button @click="retry" class="retry-btn">重试</button>
      </div>

      <!-- 空状态 -->
      <div v-else-if="orderList.length === 0" class="empty-state">
        <i class="fa fa-file-text"></i>
        <p>暂无订单</p>
        <router-link to="/" class="go-shopping">去购物</router-link>
      </div>

      <!-- 订单列表 -->
      <div v-else class="order-list">
        <div v-for="order in filteredOrderList" :key="order.order_id" class="order-item">
          <div class="order-header">
            <div class="order-info">
              <span class="order-no">订单号：{{ order.order_no }}</span>
              <span class="order-time">{{ formatDate(order.create_time) }}</span>
            </div>
            <div class="order-status" :class="`status-${order.order_status}`">
              {{ order.order_status_text || order.order_status }}
            </div>
          </div>

          <div class="order-goods" v-if="order.goods_list && order.goods_list.length">
            <div v-for="goods in order.goods_list" :key="goods.goods_id" class="goods-item">
              <div class="goods-image">
                <img :src="goods.goods_image" :alt="goods.goods_name" />
              </div>
              <div class="goods-info">
                <h4 class="goods-name">{{ goods.goods_name }}</h4>
                <p class="goods-price">¥{{ formatAmount(goods.goods_price) }}</p>
                <p class="goods-quantity">x {{ goods.goods_num }}</p>
              </div>
            </div>
          </div>

          <div class="order-footer">
            <div class="order-total">
              共{{ order.goods_list?.length || 0 }}件商品，合计：
              <span class="total-amount">¥{{ formatAmount(order.total_amount) }}</span>
            </div>
            <div class="order-actions">
              <!-- 调试信息 -->
              <span style="display: none">订单状态: {{ order.order_status }}</span>

              <!-- 待付款状态 -->
              <button
                v-if="order.order_status === OrderStatus.PendingPayment"
                class="pay-btn"
                @click="payOrder(order.order_id)"
              >
                立即付款
              </button>
              <button
                v-if="order.order_status === OrderStatus.PendingPayment"
                class="cancel-btn"
                @click="cancelOrder(order.order_id)"
              >
                取消订单
              </button>

              <!-- 待发货状态 -->
              <button
                v-if="order.order_status === OrderStatus.Shipped"
                class="refund-btn"
                @click="refundOrder(order.order_id)"
              >
                申请退款
              </button>

              <!-- 待收货状态 -->
              <button
                v-if="order.order_status === OrderStatus.Delivered"
                class="confirm-btn"
                @click="confirmOrder(order.order_id)"
              >
                确认收货
              </button>

              <!-- 已完成状态 -->
              <button
                v-if="order.order_status === OrderStatus.Completed"
                class="review-btn"
                @click="reviewOrder(order.order_id)"
              >
                评价订单
              </button>

              <!-- 通用按钮 -->
              <button class="detail-btn" @click="viewOrderDetail(order.order_id)">查看详情</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 分页 -->
    <div v-if="totalPages > 1" class="pagination">
      <button :disabled="currentPage === 1" @click="goToPage(currentPage - 1)" class="page-btn">
        上一页
      </button>
      <span class="page-info"> 第 {{ currentPage }} 页，共 {{ totalPages }} 页 </span>
      <button
        :disabled="currentPage === totalPages"
        @click="goToPage(currentPage + 1)"
        class="page-btn"
      >
        下一页
      </button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import {
  ordersApi,
  type OrderListItem,
  OrderStatus,
  getOrderStatusName,
  formatAmount,
} from '@/api/orders'
import { useOrderStore } from '@/stores/useOrderStore'
import { ElMessage, ElMessageBox } from 'element-plus'

// 路由和store
const router = useRouter()
const orderStore = useOrderStore()

// 响应式数据
const loading = computed(() => orderStore.loading)
const error = computed(() => !!orderStore.error)
const errorMessage = computed(() => orderStore.error || '')
const orderList = computed(() => orderStore.orders)

const filterStatus = ref<string>('')
const searchKeyword = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 计算属性
const totalPages = computed(() => {
  return Math.ceil(total.value / pageSize.value)
})

// 过滤后的订单列表
const filteredOrderList = computed(() => {
  let filtered = orderList.value

  // 按状态筛选
  if (filterStatus.value !== '') {
    const statusNum = parseInt(filterStatus.value)
    filtered = filtered.filter((order) => order.order_status === statusNum)
  }

  // 按关键词搜索
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase()
    filtered = filtered.filter(
      (order) =>
        order.order_no.toLowerCase().includes(keyword) ||
        order.goods_list?.some((goods) => goods.goods_name.toLowerCase().includes(keyword)),
    )
  }

  return filtered
})

// 方法
const formatDate = (dateString: string) => {
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
  })
}

const fetchOrders = async () => {
  try {
    await orderStore.fetchOrders()
    total.value = orderStore.orders.length

    // 调试：打印所有订单状态
    console.log('订单列表数据:', orderStore.orders)
    orderStore.orders.forEach((order) => {
      console.log(
        `订单 ${order.order_no} 状态:`,
        order.order_status,
        '状态文本:',
        order.order_status_text,
        'OrderStatus枚举:',
        OrderStatus[order.order_status],
      )
    })
  } catch (err) {
    console.error('获取订单列表失败:', err)
  }
}

const searchOrders = () => {
  // 本地搜索，不需要重新请求API
  currentPage.value = 1
}

const retry = () => {
  fetchOrders()
}

const payOrder = (orderId: number) => {
  router.push({
    path: '/payment',
    query: {
      order_id: orderId.toString(),
    },
  })
}

const confirmOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确认收货后无法撤销，确定要确认收货吗？', '确认收货', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await ordersApi.confirmOrder(orderId)
    ElMessage.success('确认收货成功')
    fetchOrders()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('确认收货失败:', err)
      ElMessage.error('确认收货失败')
    }
  }
}

const cancelOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确定要取消这个订单吗？', '取消订单', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await ordersApi.cancelOrder(orderId)
    ElMessage.success('订单取消成功')
    fetchOrders()
  } catch (err) {
    if (err !== 'cancel') {
      console.error('取消订单失败:', err)
      ElMessage.error('取消订单失败')
    }
  }
}

const refundOrder = async (orderId: number) => {
  try {
    await ElMessageBox.confirm('确定要申请退款吗？', '申请退款', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    ElMessage.success('退款申请已提交，等待审核')
    // 这里需要调用退款API
  } catch (err) {
    if (err !== 'cancel') {
      console.error('申请退款失败:', err)
      ElMessage.error('申请退款失败')
    }
  }
}

const reviewOrder = (orderId: number) => {
  router.push({
    name: 'CommentPage',
    params: { goodsId: '0' }, // 这里需要传递商品ID，可以先设默认值
    query: {
      orderId: orderId.toString(),
      canComment: 'true',
    },
  })
}

const viewOrderDetail = (orderId: number) => {
  router.push(`/order/${orderId}`)
}

const goToPage = (page: number) => {
  currentPage.value = page
  fetchOrders()
}

// 监听筛选条件变化 - 现在只需要本地过滤，不需要重新请求
const watchFilterChanges = () => {
  currentPage.value = 1
}

// 监听筛选状态变化
watch(filterStatus, watchFilterChanges)
watch(searchKeyword, watchFilterChanges)

// 生命周期
onMounted(() => {
  fetchOrders()
})
</script>

<style scoped lang="scss">
.order-list-page {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;

  .page-header {
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    h2 {
      font-size: 24px;
      margin: 0;
      color: #333;
    }
  }

  .order-filter {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .filter-item {
      display: flex;
      align-items: center;
      gap: 10px;

      label {
        font-weight: 500;
        color: #333;
      }

      select,
      input {
        padding: 8px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
      }

      .search-input {
        width: 200px;
      }

      .search-btn {
        padding: 8px 16px;
        background-color: #409eff;
        color: white;
        border: none;
        border-radius: 4px;
        cursor: pointer;
        transition: all 0.3s;

        &:hover {
          background-color: #3080e0;
        }
      }
    }
  }

  .order-list-container {
    .loading-container,
    .error-container,
    .empty-state {
      text-align: center;
      padding: 80px 20px;
      background: white;
      border-radius: 8px;
      box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

      i {
        font-size: 48px;
        margin-bottom: 20px;
      }

      p {
        color: #666;
        margin-bottom: 20px;
        font-size: 16px;
      }
    }

    .loading-container {
      i {
        color: #409eff;
      }
    }

    .error-container {
      i {
        color: #f56c6c;
      }
    }

    .empty-state {
      i {
        font-size: 64px;
        color: #ccc;
        margin-bottom: 20px;
      }

      p {
        font-size: 18px;
        color: #999;
        margin-bottom: 30px;
      }

      .go-shopping {
        display: inline-block;
        padding: 12px 24px;
        background-color: #409eff;
        color: white;
        text-decoration: none;
        border-radius: 4px;
        font-size: 16px;
        transition: all 0.3s;

        &:hover {
          background-color: #3080e0;
        }
      }
    }

    .order-list {
      .order-item {
        background: white;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        margin-bottom: 20px;
        overflow: hidden;

        .order-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px 20px;
          border-bottom: 1px solid #eee;
          background-color: #f9f9f9;

          .order-info {
            .order-no {
              font-weight: bold;
              margin-right: 20px;
            }

            .order-time {
              color: #999;
            }
          }

          .order-status {
            padding: 4px 10px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;

            &.status-1 {
              background-color: #f56c6c;
              color: white;
            }

            &.status-2 {
              background-color: #409eff;
              color: white;
            }

            &.status-3 {
              background-color: #67c23a;
              color: white;
            }

            &.status-4 {
              background-color: #909399;
              color: white;
            }

            &.status-5 {
              background-color: #e6a23c;
              color: white;
            }

            &.status-6 {
              background-color: #909399;
              color: white;
            }
          }
        }

        .order-goods {
          padding: 20px;

          .goods-item {
            display: flex;
            padding: 15px 0;
            border-bottom: 1px solid #eee;

            &:last-child {
              border-bottom: none;
            }

            .goods-image {
              width: 80px;
              height: 80px;
              margin-right: 20px;
              border-radius: 4px;
              overflow: hidden;

              img {
                width: 100%;
                height: 100%;
                object-fit: cover;
              }
            }

            .goods-info {
              flex: 1;

              .goods-name {
                font-size: 16px;
                margin-bottom: 8px;
                color: #333;
              }

              .goods-price {
                color: #f56c6c;
                font-weight: bold;
                margin-bottom: 5px;
              }

              .goods-quantity {
                color: #999;
              }
            }
          }
        }

        .order-footer {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 15px 20px;
          border-top: 1px solid #eee;
          background-color: #f9f9f9;

          .order-total {
            .total-amount {
              color: #f56c6c;
              font-weight: bold;
              font-size: 18px;
            }
          }

          .order-actions {
            display: flex;
            gap: 10px;

            button {
              padding: 8px 16px;
              border: none;
              border-radius: 4px;
              cursor: pointer;
              font-size: 14px;
              transition: all 0.3s;

              &.pay-btn {
                background-color: #f56c6c;
                color: white;

                &:hover {
                  background-color: #e45a5a;
                }
              }

              &.refund-btn {
                background-color: #e6a23c;
                color: white;

                &:hover {
                  background-color: #d4821f;
                }
              }

              &.confirm-btn {
                background-color: #67c23a;
                color: white;

                &:hover {
                  background-color: #5daf34;
                }
              }

              &.review-btn {
                background-color: #409eff;
                color: white;

                &:hover {
                  background-color: #3080e0;
                }
              }

              &.cancel-btn {
                background-color: #909399;
                color: white;

                &:hover {
                  background-color: #82848a;
                }
              }

              &.detail-btn {
                background-color: #409eff;
                color: white;

                &:hover {
                  background-color: #3080e0;
                }
              }
            }
          }
        }
      }
    }
  }

  .pagination {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 20px;
    margin-top: 30px;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);

    .page-btn {
      padding: 8px 16px;
      background-color: #f5f5f5;
      color: #666;
      border: none;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover:not(:disabled) {
        background-color: #e6e6e6;
      }

      &:disabled {
        opacity: 0.5;
        cursor: not-allowed;
      }
    }

    .page-info {
      color: #666;
    }
  }

  .retry-btn {
    padding: 12px 30px;
    background-color: #f5f5f5;
    color: #666;
    border: none;
    border-radius: 4px;
    font-size: 16px;
    cursor: pointer;
    transition: all 0.3s;

    &:hover {
      background-color: #e6e6e6;
    }
  }

  .spinner {
    width: 40px;
    height: 40px;
    margin: 0 auto 20px;
    border: 4px solid #f3f3f3;
    border-top: 4px solid #409eff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }

  @keyframes spin {
    0% {
      transform: rotate(0deg);
    }
    100% {
      transform: rotate(360deg);
    }
  }
}

@media (max-width: 768px) {
  .order-list-page {
    padding: 10px;

    .order-filter {
      flex-direction: column;
      gap: 15px;

      .filter-item {
        width: 100%;

        .search-input {
          flex: 1;
        }
      }
    }

    .order-list-container {
      .order-list {
        .order-item {
          .order-header {
            flex-direction: column;
            gap: 10px;
            align-items: flex-start;
          }

          .order-goods {
            .goods-item {
              .goods-image {
                width: 60px;
                height: 60px;
              }
            }
          }

          .order-footer {
            flex-direction: column;
            gap: 15px;
            align-items: flex-start;

            .order-actions {
              width: 100%;
              flex-wrap: wrap;
            }
          }
        }
      }
    }

    .pagination {
      flex-direction: column;
      gap: 15px;
    }
  }
}
</style>
